class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            target: {
                name: '',
                describe: '',
                number: '',
                time: ''
            },
            list: [
            ],
            total: 0,
            ishide: 'none',
            counts: [],
            cate: [],
            start: 0,
            pagesize: 12,
            keyword: '',
            showswitch: !0,
            pagestart: 0,
            clicknew: !1,
            id: 0,
            isshow: 1,
            imgsrc: "",
            audiosrc: "",
            musicclass: '',
            // shelf:'1',
            cid: "0",
            fileimgshow: !0,
            fileaudioshow: !0
        };
    }


    //初始化列表
    formatlist(list) {
        console.log(list.length, 'list.length')
        var listitem = [];
        console.log(list, 'formamamama')
        if (list.length > 0) {
            list.forEach((x, i) => {
                listitem.push(
                    <tr key={i}>
                        <td >
                            <div class="centerc">
                                <img src={x.info.avatarUrl ? x.info.avatarUrl : ''}></img>
                                <p>{x.info.nickName ? x.info.nickName : '匿名用户'}</p>
                            </div>
                        </td>
                        {/* <td>{x.info.nickName ? x.info.nickName : '匿名用户'}</td> */}
                        < td > {x.count}</td >
                        <td className='operate' id={"ope" + x.id}>
                            {/* <p className='edit' onClick={this.todetail.bind(this, x.id)}>查看</p> */}
                            {/* <p className={`${x.state == "ON" ? 'red' : ''} edit`} onClick={this.setshow.bind(this, x.id, x.state)}>{x.state == "ON" ? "下架" : "上架"}</p> */}
                            <p className='edit' onClick={this.del.bind(this, x.info.id)}>删除</p>
                        </td>
                    </tr >
                )
            })
            // list.forEach((x, i) => {
            //     cate.forEach((y, j) => {
            //         if (y.id == x.cid) {
            //             nameclass = y.name
            //         }
            //     })
            //     listitem.push(
            //         <tr key={i}>
            //             <td><img className="tdimg" src={`${API_HEAD}imgs/${x.thumbpath}`} /></td>
            //             <td>{x.title}</td>
            //             <td className="describe"><p>{x.description}</p></td>
            //             <td><p>{nameclass}</p></td>
            //             <td>{x.views > 10000 ? `${Math.floor(x.views / 10000)}万` : x.views}</td>
            //             <td><audio src={`${Constant.AUDIOSRC}/${x.src}`} controls="controls">Your browser does not support the audio tag.</audio></td>
            //             <td>{x.orders}</td>
            //             <td className='operate' id={"ope" + x.id}>
            //                 <p className='edit' onClick={this.todetail.bind(this, x.id)}>编辑</p>
            //                 <p className={`${x.state == "ON" ? 'red' : ''} edit`} onClick={this.setshow.bind(this, x.id, x.state)}>{x.state == "ON" ? "下架" : "上架"}</p>
            //                 <p className='edit' onClick={this.del.bind(this, x.id)}>删除</p>
            //             </td>
            //         </tr>
            //     )
            // });
        } else {
            listitem.push(
                <tr key='0'>暂无数据</tr>
            )
        }
        this.setState({ listitem, list, originallist: list })
        console.log(this.state.listitem, 'ititititi')
    }
    // 编辑
    todetail(e) {


        // var { list,imgsrc, audiosrc,musicclass,shelf} = this.state, item = [];
        // console.log(e, 'eeee')
        // console.log(list, 'list')
        // list.forEach(x => {
        //     if (x.id == e) {
        //         imgsrc=`${API_HEAD}imgs/${x.thumbpath}`
        //         audiosrc=`${Constant.AUDIOSRC}/${x.src}`
        //         // shelf=x.state=="ON"?"0":"1"
        //         musicclass=x.cid
        //         // $(`input[value=${shelf}]`).prop("checked","checked");
        //         $(`input[value=${musicclass}]`).prop("checked","checked");
        //         item = { name: x.title,describe:x.description, number: x.orders,time:x.duration}
        //     }
        // });
        // console.log(item, 'item')
        // this.setState({ id: e, target: item, clicknew: !0,imgsrc,audiosrc,shelf,musicclass,fileimgshow:!1,fileaudioshow:!1,imgstate:'isBase64',audiostate:'isuploadaudio'})
    }





    // 上架下架
    setshow(e, i) {
        let { start } = this.state
        audiosetstate(e, res => {
            if (res.issuccess == 1) {
                alert(`${i == "OFF" ? '上架' : '下架'}成功`)
                this.freshlist(start)
            }
        })

    }

    // 删除
    del(e) {

        this.setState({ delid: e }, () => {
            $('#myModal').modal('toggle');
        })

    }
    //弹窗确定
    confirmdel() {
        let { delid, pagesize, start } = this.state
        delcollection({ userid: delid, pagesize, start }, res => {
            if (res.issuccess == 1) {
                this.formatlist(res.list)
                alert('删除成功')
                $('#myModal').modal('toggle');
            }
        })
    }

    inputchange(prop, e) {
        // console.log(prop, 'prop')
        // console.log(e.target.value, 'eeee')
        let { target } = this.state;
        target[prop] = e.target.value
        this.setState({ target })
        // this.setState({ [prop]:e.target.value }) 
    }
    inputchangeradio(prop, e) {
        console.log(prop, 'prop')
        console.log(e.target.value, 'eeee')
        this.setState({ [prop]: e.target.value })
    }
    // 点击新建或编辑
    getnew(start) {
        this.setState({ clicknew: !this.state.clicknew, id: '0' });
    }

    submit() {
        var { start, imgsrc, audiosrc, imgstate, audiostate, shelf, musicclass, cate, cid } = this.state, pathaudio = "", pathimg = "", _this = this, err = '', { name, describe, number, time } = this.state.target;
        time = Number(time)
        number = Number(number)
        // console.log(number, 'number')
        // console.log(audiosrc, 'audiosrc')
        var reg = /^[0-9]{1,3}$/
        if (audiostate != "isuploadaudio") err = "请上传音频"
        if (imgstate != "isBase64") err = "请上传图片"
        if (isNaN(time) || time <= 0) err = "请输入音频时长"
        if (!reg.test(number)) {
            err = "请输入整数"
        }
        if (number > 100 || number < 0 || number == "") err = "请输入0-100的数字"
        if (!audiosrc) err = "请添加音频"
        if (describe == "") err = "请输入描述"
        if (musicclass.length == 0) err = "请选择音频分类"
        // if(shelf.length==0) err = "请选择是否上架"
        if (name == "") err = "请输入名称"
        if (!imgsrc) err = "请添加封面"
        if (err.length > 0) {
            alert(err);
            return
        }
        pathimg = imgsrc.replace(`${API_HEAD}imgs/`, '')
        pathaudio = audiosrc.replace(`${Constant.AUDIOSRC}/`, '')
        var submitdata = { title: name, description: describe, src: pathaudio, thumbpath: pathimg, orders: number, cid: musicclass, duration: time }
        if (this.state.id > 0) submitdata['id'] = this.state.id;

        audioaoe(submitdata, res => {
            if (res.issuccess == 1) {
                alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                _this.setState({
                    clicknew: !1,
                    // target:''
                })
                _this.freshlist(start)
            }
        })

    }
    searchinput(e) {
        // console.log(e.target.value,'e.target.value')
        this.setState({ keyword: e.target.value })
    }
    // 排序
    // search(){
    //     if(this.state.keyword.length==0) return;
    //     let {keyword} = this.state;

    // audiocatesetorder(keyword,res=>{
    //     if(res.issuccess==1){
    //         // console.log(res,'res.data')
    //         this.formatlist(res.data);
    //         this.setState({showswitch:!1})
    //     }
    // })

    // }
    reset() {
        this.setState({ keyword: '', showswitch: !0 });
        this.freshlist(0, 'ALL');
    }
    inputchangeall() {

    }

    //初始化
    componentDidMount() {
        this.freshlist(0)

    }

    //刷新列表
    freshlist(start) {
        let { pagesize, list, total } = this.state;
        // console.log(start, pagesize)
        getcollectionlist({ start: start, pagesize }, res => {
            this.setState({
                list: res.list
            })
            console.log(this.state.list, this.state.total, '123546')
            if (start == 0) {
                let pagecount = Math.ceil(res.total / pagesize);
                this.setpager(pagecount, start);
                this.setState({ start })
            }
            this.formatlist(res.list);
        })


        // audiogetlist({ pagesize, start, isback: 1, cid }, res => {
        //     if (res.issuccess == 1) {
        //         if (start == 0) {
        //             let pagecount = Math.ceil(res.total / pagesize);
        //             this.setpager(pagecount, start);
        //             this.setState({ start, })
        //         }
        //         this.formatlist(res.list);
        //     }
        // })


    }
    inputlist(list) {
        var inputhtml = []
        list.forEach((x, i) => {
            inputhtml.push(
                <div key={i} className="radio"><input type="radio" name="radio" value={x.id} /><span>{x.name}</span></div>
            )
        })
        this.setState({ inputhtml, cate: list })
    }

    setpager(pagecount, start) {
        let counts = [];
        for (let i = 1; i < pagecount + 1; i++) {
            counts.push(start + i)
        }
        this.setState({ counts })
    }


    clickpage(e) {
        let { start, pagesize } = this.state
        start = e * pagesize
        this.setState({ pagestart: e, start }, () => {
            this.freshlist(start)
        })
    }
    // 预览图片
    filechangeimg(e) {
        // this.setState({
        //     fileimgshow:!1,
        //     // uploadword: "上传",
        //     imgstate:''
        // })  
        var that = this;
        // var filedata = $('#file3')[0].files[0];
        var filedata = $('#file3')[0].files[0];
        let _name, _fileName;
        _name = $('#file3')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            this.setState({
                fileimgshow: !1,
                // uploadword: "上传",
                imgstate: ''
            })
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str])
            }
        }
    }
    putswiperimglistdata(target) {


        let { imgsrc } = this.state;
        imgsrc = target[0]
        if (!isBase64(imgsrc)) {
            if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                imgsrc = `${API_HEAD}imgs/${src}`

            }
        }
        this.setState({
            imgsrc
        })

    }
    // 试听音频
    filechangeaudio(e) {
        let fileaudio = $('#file0')[0].files[0];
        let _name, _fileName;
        _name = $('#file0')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "mp3" && _fileName !== "wma" && _fileName !== "MP1" && _fileName !== "MP2" && _fileName !== "MPEG") {
            alert("上传音频格式不正确，请重新上传");
        } else {
            this.setState({
                // uploadword: "上传",
                fileaudio,
                audiostate: ''
            })
        }
    }

    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(e) {
        console.log(e, 'eeeeeeee')
        if (e == 3) {
            this.setState({
                imgsrc: '',
                fileimgshow: !0,
                imgstate: ''
            })
        } else if (e == 0) {
            this.setState({
                audiosrc: '',
                fileaudioshow: !0,
                audiostate: ''
            })
        }
    }
    // 上传图片
    uploadimg(e) {
        let { imgsrc, imgstate } = this.state;
        if ((imgstate == "isBase64")) {
            return;
        }
        if (imgsrc) {
            if (isBase64(imgsrc)) {
                uploadimg(imgsrc, res => {
                    if (res.issuccess == 1) {
                        imgsrc = `${API_HEAD}imgs/${res.path}`
                        // imghtml.push(
                        //     <div className="img_warp">
                        //         <img src={imgsrc} className="img" />
                        //         <img className='closeimg' onClick={this.del_img.bind(this,e)} src='./src/img_close.png' />
                        //     </div>
                        // )
                        this.setState({ fileimgshow: !1, imgsrc, imgstate: 'isBase64' })
                    } else {
                        alert(res.msg)
                        err = 1
                        return;
                    }
                })
            }

        }

    }
    // 上传音频
    uploadaudio(e) {
        let { audiosrc, fileaudio, audiostate } = this.state;
        if (audiostate == 'isuploadaudio') {
            return;
        }
        if (fileaudio) {
            uploadaudio(fileaudio, res => {
                console.log(res, 'res');
                if (res.success == 1) {
                    audiosrc = `${Constant.AUDIOSRC}/${res.path}`
                    // audiohtml.push(
                    //     <div className="audio_warp">
                    //         <audio src={audiosrc} controls="controls" id="audio">Your browser does not support the audio tag.</audio>
                    //         <button className="delaudio" onClick={this.del_img.bind(this,e)}>删除</button>
                    //     </div>
                    // )
                    this.setState({ fileaudioshow: !1, audiosrc, audiostate: 'isuploadaudio' })

                } else {
                    alert(res.msg)
                    err = 1
                    return;
                }
            })
        }
    }
    onstatechange(e) {
        let { cid } = this.state, estate = e.target.value;
        console.log(cid, 'cid');
        console.log(e.target.value, 'e.target.value');

        if (cid == estate) return;
        this.setState({ start: 0, cid: estate }, () => {
            this.freshlist(0)
        })
    }
    render() {
        let { clicknew, counts, listitem, pagestart, keyword, showswitch, target, inputhtml, imgsrc, audiosrc } = this.state;

        return (
            <div>
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />
                <div className='content_wrap panel-default content_wrap'>

                    <div className='breadLine '>
                        当前位置 > 收藏管理
                        </div>
                    {/* <div className='btns'>
                        <button className='btn add btn-primary center ' onClick={this.getnew.bind(this)} id='btnimg_add'> <img src={Constant.ADD} />  {this.state.id == 0 ? "新建" : "编辑"}名称</button>
                    </div> */}

                    <div style={{ display: clicknew ? "" : "none" }} id="div">
                        <div className="input-group">
                            <span className="input-group-addon">封面</span>
                            <input onChange={this.filechangeimg.bind(this, '3')} type='file' id='file3' style={{ display: "none" }} />
                            <div className='detail_btns'>
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 3)} style={{ display: this.state.fileimgshow ? "" : "none" }} />
                                {/* {this.state.imghtml} */}
                                <div className="img_warp" style={{ display: this.state.fileimgshow ? "none" : "" }}>
                                    <img src={imgsrc} className="img" />
                                    <img className='closeimg' onClick={this.del_img.bind(this, 3)} src='./src/img_close.png' style={{ display: this.state.fileimgshow ? "none" : "" }} />
                                </div>
                                <button onClick={this.uploadimg.bind(this)} className={`btn addpart btn-${this.state.imgstate == "isBase64" ? 'success' : 'primary'} center w20`} >{this.state.imgstate == "isBase64" ? '上传成功' : '上传图片'}</button>
                                {/* <button onClick={this.uploadimg.bind(this,3)} className={`btn addpart btn-primary center w20`} >上传图片</button>
                                    <span className="fileshow" style={{display:this.state.imgstate=="isBase64" ?"":"none"}}>已上传</span> */}
                            </div>
                        </div>
                        <div className="input-group">
                            <span className="input-group-addon">名称</span>
                            <input id='name' onChange={this.inputchange.bind(this, 'name')} value={target.name} type="text" placeholder='请输入分类名称' className="form-control" />
                        </div>
                        {/* <div className="input-group countrys">
                            <span className="input-group-addon">是否上架</span>
                            <div className="countryname" onChange={this.inputchangeradio.bind(this,'shelf')}>
                                <div className="radio"><input type="radio" name="shelf" value="0"/><span>上架</span></div>
                                <div className="radio"><input type="radio" name="shelf" value="1"/><span>下架</span></div>
                            </div>
                        </div> */}
                        <div className="input-group countrys">
                            <span className="input-group-addon">音频分类</span>
                            <div className="countryname" onChange={this.inputchangeradio.bind(this, 'musicclass')}>
                                {inputhtml}
                            </div>
                        </div>
                        <div className="input-group">
                            <span className="input-group-addon">描述</span>
                            <textarea id='describe' onChange={this.inputchange.bind(this, 'describe')} value={target.describe} className="form-control describe" placeholder='请输入描述' rows="10"></textarea>
                        </div>
                        <div className="input-group">
                            <span className="input-group-addon">音频</span>
                            <input onChange={this.filechangeaudio.bind(this, '0')} onClick={this.clickupload.bind(this, 0)} type='file' id='file0' style={{ display: this.state.fileaudioshow ? "" : "none" }} />
                            <div className='detail_btns'>
                                {/* {this.state.audiohtml} */}
                                <div className="audio_warp" style={{ display: this.state.fileaudioshow ? "none" : "" }}>
                                    <audio src={audiosrc} controls="controls" id="audio">Your browser does not support the audio tag.</audio>
                                    <button className="delaudio" onClick={this.del_img.bind(this, 0)}>删除</button>
                                </div>
                                <button onClick={this.uploadaudio.bind(this)} className={`btn addpart btn-${this.state.audiostate == "isuploadaudio" ? 'success' : 'primary'} center w20`} >{this.state.audiostate == "isuploadaudio" ? '上传成功' : '上传文件'}</button>
                                {/* <button onClick={this.uploadaudio.bind(this,0)} className={`btn addpart btn-primary center w20`} >上传文件</button> */}
                                {/* <span className="fileshow" style={{display:this.state.audiostate=="isuploadaudio" ?"":"none"}}>已上传</span> */}
                            </div>
                        </div>
                        <div className="input-group">
                            <span className="input-group-addon">排序</span>
                            <input id='name' onChange={this.inputchange.bind(this, 'number')} value={target.number} type="text" placeholder='请输入0-100的数字' className="form-control" />
                            <span className="red">数值越大，排名越前</span>
                        </div>
                        <div className="input-group">
                            <span className="input-group-addon">时长</span>
                            <input id='name' onChange={this.inputchange.bind(this, 'time')} value={target.time} type="text" placeholder='请输入音频时长' className="form-control" />
                            <span className="red">单位：秒</span>
                        </div>
                        <div className='btns_bottom center'>
                            <button className='btn add btn-primary center w20' onClick={this.submit.bind(this)} id='btnimg_save' style={{ marginLeft: 50 }}>保存</button>
                        </div>
                    </div>
                    {/* <div className='search'>
                        <p>选择状态:</p>
                        <select value={this.state.cid} onChange={this.onstatechange.bind(this)} className="form-control select">
                            {this.state.statehtml}
                        </select>
                    </div> */}
                    <table className="table table-hover">
                        <thead>
                            <tr>
                                <th>头像</th>
                                <th>收藏数目</th>
                                <th className="cz">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {listitem}
                        </tbody>
                    </table>

                    <div style={{ display: showswitch ? "" : "none" }}><Pager counts={counts} click={this.clickpage.bind(this)} index={pagestart} /></div>


                </div>

            </div>


        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='collection' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)
